﻿///<reference path="TextSelection.ts"/>
///<reference path="TextFont.ts"/>
///<reference path="TextCursor.ts"/>

class TextDocument implements ITextViewDelegate
{
    private _storage: string[];

    constructor(text: string = "")
    {
        this._storage = this._prepareText(text);
    }

    private _prepareText(text: string): string[]
    {
        var lines:string[] = [], index:number = 0, newIndex:number;
        do
        {
            newIndex = text.indexOf("\n", index);
            lines.push(text.substr(index, newIndex !== -1 ? newIndex - index + 1 : void 0));
            index = newIndex + 1;
        } while (newIndex !== -1);

        return lines;
    }

    lineCount(): number
    {
        return this._storage.length;
    }

    lineLength(line: number): number
    {
        return this._storage[line].trim().length;
    }

    getLineText(line: number): string
    {
        return this._storage[line];
    }

    appendTextLinesAtPosition(text: string,position:TextPosition):TextPosition
    {
        var lines = this._prepareText(text);
        var newCharacterPos = lines[lines.length - 1].length;
        if (lines.length === 1)
            newCharacterPos += position.character;

        lines[lines.length - 1] += this._storage[position.line].substr(position.character);

        this._storage[position.line] = this._storage[position.line].substr(0, position.character) + lines[0];

        var args = [];
        args = args.concat([position.line + 1, 0]);
        args = args.concat(lines.slice(1));
        this._storage.splice.apply(this._storage, args);

        return new TextPosition(position.line + lines.length - 1, newCharacterPos);
    }

    deleteTextWithRange(range: TextSelectionRange): TextPosition
    {
        if ((range.start.character !== range.end.character) || (range.start.line !== range.end.line))
        {
            var startLine = range.start.line;
            var startCharacter = range.start.character;
            var endLine = range.end.line;
            var endCharacter = range.end.character;

            this._storage[startLine] = this._storage[startLine].substr(0, startCharacter) +
                this._storage[endLine].substr(endCharacter);

            this._storage.splice(startLine + 1, endLine - startLine);
        }
        return range.start;
    }
}